package com.ymttest.datadriver;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.ymt.base.YmatouBaseCall;
import com.ymt.core.tool.Logger;
import com.ymttest.utils.JsonBeanHelper;

public class APICallImpl implements APICall{
	private YmatouBaseCall ymatouBaseCall;
	private String ClassName;
	
	
	public APICallImpl(String ClassName){
		setApiCall(ClassName);
	}
	
	
	private void setApiCall(String ClassName){
		try{
			@SuppressWarnings("rawtypes")
			Class clz = Class.forName(ClassName);
			ymatouBaseCall= (YmatouBaseCall)clz.newInstance();
			this.ClassName = ClassName;
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	@Override
	public String getMode() {
		if (ClassName.contains("Login")){
			return "POST";
		}
		return "GET";
	}

	@Override
	public String getSysUrl() {
		return null;
	}

	@Override
	public String getApi() {
		return null;
	}

	
	/***
	 * call api and get return data
	 * add request message and cookies if has
	 */
	@Override
	public JSONObject callAndGetReturnData(JSONObject params){
		try{
			if(getMode().equals("GET")){
				ymatouBaseCall.setData(params);
				
			}else{
				
				String paramStr = params.toString().replaceAll("\\{", "").replaceAll("\\}", "").replaceAll(":", "=").replaceAll(",", "&").replaceAll("\"", "");
				ymatouBaseCall.setData(paramStr);
			}
			
			ymatouBaseCall.callService();	
			JSONObject retJson ;
			try{
				retJson = new JSONObject(ymatouBaseCall.getReturnData()).getJSONObject("Data");
			}catch (JSONException e) {
				Logger.comment("result is not json format");
				retJson = new JSONObject();
			}
			
			retJson.put(JsonBeanHelper.JsonBeanRequest,params);
			retJson.put("cookies", ymatouBaseCall.getCookies());
			return  retJson;
			
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
		
	}

	@Override
	public List<String> getCookies() {
		return ymatouBaseCall.getCookies();
	}

	@Override
	public void setCookies( String cookies) {
		ymatouBaseCall.setCookie(cookies);
	}

	
}
